package com.kalvan.core.autoconfigure;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AspectJTypeFilter;
import org.springframework.core.type.filter.TypeFilter;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 自动扫描kalvan框架包
 *
 * @author chenliang
 */
public class KalvanSelector implements ImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata metadata) {
        // 1. 定义扫描包的名称
        String[] basePackages = null;
        // 2. 判读 @Import注解的类上有没有@ComponentScan注解
        if (metadata.hasAnnotation(ComponentScan.class.getName())) {
            // 3. 取出ComponentScan注解的属性(basePackage/value)
            Map<String, Object> attributes = metadata.getAnnotationAttributes(ComponentScan.class.getName());
            // 4. 取出basePackages属性的值
            assert attributes != null;
            basePackages = (String[]) attributes.get("basePackages");
        }
        // 5. 判读是否有此注解，是否指定了包扫描的信息, 如果没有此注解，则扫描
        // @Import 类所在包及其子包
        if (basePackages == null || basePackages.length == 0) {
            String basePackage = null;
            try {
                // 6. 取出 @Import 所在包的包名
                basePackage = Class.forName(metadata.getClassName()).getPackage().getName();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            // 7. 把包名填充到basePackages中
            basePackages = new String[]{basePackage};
        }
        // 8.创建类路径扫描器 false 表示 不使用默认扫描规则
        ClassPathScanningCandidateComponentProvider scan = new ClassPathScanningCandidateComponentProvider(false);
        // 9. 创建类型过滤器
//        Properties properties = PropertiesLoaderUtils.loadAllProperties("costumer.properties");
//        String expression = properties.getProperty("custome.selector.expression");
        TypeFilter typeFilter = new AspectJTypeFilter("com.kalvan.*", KalvanSelector.class.getClassLoader());
//      10. 把类型过滤器加入到扫描器中
        scan.addIncludeFilter(typeFilter);
//      11. 定义要扫描类的全限定类名
        final Set<String> classes = new HashSet<>();
        // 12.填充集合的类型
        for (String aPackage : basePackages) {
            Set<BeanDefinition> beanDefinitions = scan.findCandidateComponents(aPackage);
            for (BeanDefinition beanDefinition : beanDefinitions) {
                classes.add(beanDefinition.getBeanClassName());
            }
        }
        return classes.toArray(new String[0]);
    }
}

